const { Activity, Banner } = require('./model');
const { Op } = require('sequelize');

class ActivityDao {
  // 活动相关操作
  
  // 创建活动
  async createActivity(activityData) {
    try {
      return await Activity.create(activityData);
    } catch (error) {
      throw new Error(`创建活动失败: ${error.message}`);
    }
  }

  // 获取活动列表
  async getActivities(options = {}) {
    try {
      const { page = 1, limit = 10, status, keyword } = options;
      const offset = (page - 1) * limit;
      
      const whereClause = {};
      if (status) whereClause.status = status;
      if (keyword) {
        whereClause[Op.or] = [
          { title: { [Op.like]: `%${keyword}%` } },
          { description: { [Op.like]: `%${keyword}%` } }
        ];
      }

      const { count, rows } = await Activity.findAndCountAll({
        where: whereClause,
        order: [['start_time', 'DESC']],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      return {
        activities: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      };
    } catch (error) {
      throw new Error(`获取活动列表失败: ${error.message}`);
    }
  }

  // 根据ID获取活动
  async getActivityById(id) {
    try {
      return await Activity.findByPk(id);
    } catch (error) {
      throw new Error(`获取活动失败: ${error.message}`);
    }
  }

  // 获取当前进行中的活动
  async getActiveActivities() {
    try {
      const now = new Date();
      return await Activity.findAll({
        where: {
          status: 'active',
          start_time: { [Op.lte]: now },
          end_time: { [Op.gte]: now }
        },
        order: [['start_time', 'ASC']]
      });
    } catch (error) {
      throw new Error(`获取进行中活动失败: ${error.message}`);
    }
  }

  // 更新活动
  async updateActivity(id, updateData) {
    try {
      const [updatedRowsCount] = await Activity.update(updateData, {
        where: { id }
      });
      
      if (updatedRowsCount === 0) {
        throw new Error('活动不存在');
      }
      
      return await this.getActivityById(id);
    } catch (error) {
      throw new Error(`更新活动失败: ${error.message}`);
    }
  }

  // 增加活动参与人数
  async incrementParticipantCount(id) {
    try {
      const activity = await this.getActivityById(id);
      if (!activity) {
        throw new Error('活动不存在');
      }

      return await this.updateActivity(id, {
        participant_count: activity.participant_count + 1
      });
    } catch (error) {
      throw new Error(`增加参与人数失败: ${error.message}`);
    }
  }

  // 删除活动
  async deleteActivity(id) {
    try {
      const deletedRowsCount = await Activity.destroy({
        where: { id }
      });
      
      if (deletedRowsCount === 0) {
        throw new Error('活动不存在');
      }
      
      return true;
    } catch (error) {
      throw new Error(`删除活动失败: ${error.message}`);
    }
  }

  // 轮播图相关操作

  // 创建轮播图
  async createBanner(bannerData) {
    try {
      return await Banner.create(bannerData);
    } catch (error) {
      throw new Error(`创建轮播图失败: ${error.message}`);
    }
  }

  // 获取轮播图列表
  async getBanners(options = {}) {
    try {
      const { page = 1, limit = 10, status } = options;
      const offset = (page - 1) * limit;
      
      const whereClause = {};
      if (status) whereClause.status = status;

      const { count, rows } = await Banner.findAndCountAll({
        where: whereClause,
        order: [['sort', 'ASC'], ['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      return {
        banners: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      };
    } catch (error) {
      throw new Error(`获取轮播图列表失败: ${error.message}`);
    }
  }

  // 获取活跃的轮播图
  async getActiveBanners() {
    try {
      return await Banner.findAll({
        where: { status: 'active' },
        order: [['sort', 'ASC'], ['created_at', 'DESC']]
      });
    } catch (error) {
      throw new Error(`获取活跃轮播图失败: ${error.message}`);
    }
  }

  // 根据ID获取轮播图
  async getBannerById(id) {
    try {
      return await Banner.findByPk(id);
    } catch (error) {
      throw new Error(`获取轮播图失败: ${error.message}`);
    }
  }

  // 更新轮播图
  async updateBanner(id, updateData) {
    try {
      const [updatedRowsCount] = await Banner.update(updateData, {
        where: { id }
      });
      
      if (updatedRowsCount === 0) {
        throw new Error('轮播图不存在');
      }
      
      return await this.getBannerById(id);
    } catch (error) {
      throw new Error(`更新轮播图失败: ${error.message}`);
    }
  }

  // 删除轮播图
  async deleteBanner(id) {
    try {
      const deletedRowsCount = await Banner.destroy({
        where: { id }
      });
      
      if (deletedRowsCount === 0) {
        throw new Error('轮播图不存在');
      }
      
      return true;
    } catch (error) {
      throw new Error(`删除轮播图失败: ${error.message}`);
    }
  }

  // 批量更新轮播图排序
  async updateBannerSort(sortData) {
    try {
      const promises = sortData.map(item => 
        Banner.update({ sort: item.sort }, { where: { id: item.id } })
      );
      
      await Promise.all(promises);
      return true;
    } catch (error) {
      throw new Error(`更新轮播图排序失败: ${error.message}`);
    }
  }
}

module.exports = new ActivityDao();
